﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using OBUCare.Web.Models;
using OBUCare.Core.DataAccess;
using OBUCare.Core.BL;
using OBUCare.Core.Models;
using OBUCare.Web.Infrastructure;
using OBUCare.Core.Common;
namespace OBUCare.Web.Controllers
{
    public class UserReceiveObuController : Controller
    {

        private OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();
        //static REPAIR_ORDERS repairOrder = null;
        //
        // GET: /UserReceiveObu/

        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 用户输入标签后现实标签信息和维修单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult obuInfoControl(string id)
        {
            var result = getUserObuInfo(id);

            if (result != null && result.RepairOrder.STATUS == RepairOrderStatus.InformedCustomer.ToInt())
            {
                return PartialView("obuInfoControl", result);
            }
            else
            {
                return PartialView("NullInfoControl", result);
            }
        }
        private UserReceiveObuInfo getUserObuInfo(string id)
        {
            string[] strs = id.Split(',');
            string orderNo = strs[0];
            string obuNo = strs[1];

            string sqlWhere = " 1=1 ";
            if (orderNo != "")
                sqlWhere += " AND REPAIR_ORDER_NO='" + orderNo + "'";
            if (obuNo != "")
                sqlWhere += " AND OBU_NO='" + obuNo + "'";
            //如果传入的值是维修单号，则先根据维修单号获取标签基本信息
            View_RepariOrders repairOrders = null;
            //if (obuNo.IsNullOrEmpty())
            //{

            var partResult = obuMgr.GetRepairOrders(sqlWhere + " AND STATUS =" + RepairOrderStatus.InformedCustomer.ToInt());

            if (partResult != null && partResult.Count() > 0)
                repairOrders = partResult.First();
            else
            {
                partResult = obuMgr.GetRepairOrders(sqlWhere);
                if (partResult != null && partResult.Count() > 0)
                    repairOrders = partResult.First();
                else
                    return null;
            }

            obuNo = repairOrders.OBU_NO;

            //var baseInfo = obuMgr.GetObuInfo(obuNo);
            //}

            //var baseInfo = obuMgr.GetObuInfo(obuNo);

            //if (repairOrders == null)
            //{
            //    var partResult = obuMgr.GetRepairOrders(sqlWhere);
            //    if (partResult != null && partResult.Count() > 0)
            //        repairOrders = partResult.First();
            //    else
            //        return null;
            //}
            //标签信息
            OPERATOR OperatorInfo = UIUtility.GetCurrentUser();
            //如果维修单信息存在则获取维修费服务费等信息
            if (repairOrders != null)
            {

                var partsList = db.PARTS_TYPE.ToList();
                //根据维修单性质ID获取维修性质名称
                REPAIR_TYPE repairType = obuMgr.getRepairTypeValueBy(repairOrders.REPAIR_TYPE);
                //根据维修单编号或标签号获取故障点及价格
                var repairFeeList = obuMgr.getRepairFee(repairOrders.ID);
                var repairFee = new List<RepairFeeModel>();

                foreach (var item in repairFeeList)
                {
                    var partsinfo = (from parts in partsList
                                     where parts.ID == item.FAULT_PARTS
                                     select parts).FirstOrDefault();

                    var alllist = new RepairFeeModel() { RepairPrice = item, PartsType = partsinfo };

                    repairFee.Add(alllist);
                }

                var repairFeeAdjust = obuMgr.getRepairFeeAdjust(repairOrders.ID, AdjustType.AdjustRepairFee).ToList();//维修费调整信息

                //var serviceFeeList = obuMgr.getRepairFeeAdjust(repairOrders.ID, AdjustType.GenerateServiceFee).ToList();//服务费

                var serviceFeeAdjust = obuMgr.getRepairFeeAdjust(repairOrders.ID, AdjustType.AdjustServiceFee).ToList();//服务费调整

                var userReceiveInfo = new UserReceiveObuInfo()
                {
                    //ObuBaseInfo = baseInfo,
                    ////OperatorInfo = OperatorInfo,
                    RepairOrder = repairOrders,
                    RepairType = repairType,
                    RepairFeeModel = repairFee,
                    RepairFeeAdjust = repairFeeAdjust,
                    //ServiceFee = serviceFeeList,
                    ServiceFeeAdjust = serviceFeeAdjust

                };
                return userReceiveInfo;
            }
            else
                return null;

        }

        /// <summary>
        /// 外部调用getUserObuInfo函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserReceiveObuInfo getUserObuInfoforOthers(string id)
        {
            return getUserObuInfo(id);
        }

        /// <summary>
        /// 提交后，更新维修单信息 增加日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult updateOrdersInfo()
        {
            try
            {

                //根据维修ID
                long RepairOrderID = long.Parse(Request.Form["Order_id"].ToString());
                var order = db.REPAIR_ORDERS.Find(RepairOrderID);
                if (order.STATUS==Convert.ToInt16(RepairOrderStatus.ClosedWithCustomerPickedBack))
                {
                    return Content("<script>alert('该标签已领取，不能再次领取');window.location.href='/UserReceiveObu/Index'</script>");
                }
                string obu_remark = "";
                if (Request.Form["obu_remark"] != null)
                    obu_remark = Request.Form["obu_remark"].ToString();
                bool returnSpareObu = false;
                if (Request.Form["returnSpareObu"] != null)
                    returnSpareObu = bool.Parse(Request.Form["returnSpareObu"].ToString());

                string userNo = Request.Form["USER_NO"].ToString();
                decimal repairFeeSum = decimal.Parse(Request.Form["repairFeeSum"].ToString());
                decimal serverFeeSum = decimal.Parse(Request.Form["serviceFeeSum"].ToString());
                decimal serviceFee = decimal.Parse(Request.Form["serviceFee"].ToString());
                string serviceRemark = "逾期" + Request.Form["infocustomerDate"].ToString() + "天*"
                    + ServiceFeeCheck.ServiceFeePrice.ToString() + "(元)";

                obuMgr.GetObuBack(RepairOrderID, returnSpareObu, obu_remark, repairFeeSum, serverFeeSum,
                    serviceFee, serviceRemark, UIUtility.GetCurrentUser());
                if ((repairFeeSum + serverFeeSum + serviceFee > 0 && order.CONFIRM_REPAIRED == ConfirmRepairedStatus.Repair.ToInt()) || order.SPARE_OBU_PRICE > 0)
                {//如果有要交钱或退钱的话就跳转至流水单管理
                    string url = "/Transaction/Index/?orderUserNo=" + userNo;
                    return Content("<Script>alert('信息提交成功！');window.location.href='" + url + "' </Script>");
                }
                else
                {
                    return Content("<Script>alert('信息提交成功！');window.location.href='/RepairOrders/List/' </Script>");
                }
                //return RedirectToAction("Index", "Transaction", new { orderUserNo = userNo });
            }
            catch (Exception e)
            {
                var msg = e.Message;
                return Content("<Script>alert('信息提交失败!');window.location.href='/Transaction/Index/';</Script>");
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            db.Dispose();
            obuMgr.Dispose();
        }
    }
}
